if (typeof String.prototype.trim !== 'function') { trim = String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); } }

function debug(e) {var s = t = ""; if ((typeof(e) == "object") || (typeof(e) == "array")) for (var i in e) {switch (t = typeof(e[i])) {case "function": case "object": case "array": break; default: t = e[i];	} s += i + " = " + t + "\n"; } else	s = e; return s;}

log = (window.console && window.console.log) ?
	(window.console.log.apply && function(){window.console.log.apply(window.console, arguments)} || window.console.log) :
	function () {};

(function($) {	// innerxhtml()
	$.fn.xhtml = function($string,$appendage) {
		var res = [];
		$(this).each( function() { res.push(innerXHTML(this,$string,$appendage)) });
		switch (res.length) {
			case 0: return "";
			case 1: return res[0];
			default: return res;
		}
	};
})(jQuery);


var xTemplate = {
	
	applyData : function(template, data, de) {
if (de) log({template:template, data:data});
		template = template.replace(/(\[|\%5B)\%([^\]]+)(\]|\%5D)/gi, function() {
			var ind = arguments[2].trim();
if (de) log({ind:ind, data:data[ind]});
			return (ind && data && (data[ind] != undefined)) ? data[ind] : arguments[0];
		});
		return template;
	},
	
	extractTemplate : function(template) { return $("<div />").append(template.clone(true).removeClass("template")).xhtml(); },

	applyArray : function(options) { // template, arr, debug
		var o = $.extend({ template: "", data: [], callback:false, debug:false }, options);
		var block_html = this.extractTemplate(o.template);
		
//		$("<div />").append(o.template.clone(true).removeClass("template")).xhtml();
		
if (o.debug) log("apply array", block_html, data);	
	
		var temp = [];
		for (var i in o.data) if (o.data.hasOwnProperty(i))
			temp.push(this.applyData(block_html, o.data[i], o.debug));
	
if (o.debug) log("applied: ", temp);
	
		temp = $(temp.join(""));

		if (o.callback) 
			o.callback(temp, o.data);

		o.template.nextAll("*").remove();
		o.template.after(temp);
	}
}